<?php
class Manager {
	
	protected static $_instances = array();

	public static function getInstance()
	{
		$class = get_called_class();
		if ( ! isset(static::$_instances[$class]) ) {
			static::$_instances[$class] = new $class();
		}
		return static::$_instances[$class];
	}

	
	/**
	 * @var Zend_Db_Adapter_Abstract
	 */
	protected $_db;
	
	protected function __construct()
	{
		$this->_db = Zend_Registry::get('db');	
	}
	
	/**
	 * @param string $class
	 * @param array $data
	 * @return array
	 */
	protected function _createCollection($class, $data)
	{
		$result = array();
		foreach ($data as $value) {
			$result[] = $this->_createObject($class, $value);
		}
		return $result;
	}
	
	protected function _createObject($class, $data)
	{
		if ($data) {
			$object = new $class($data);
			$object->setSaved();
			return $object;
		} else {
			return null;
		}
	}
	
	public function _fetchObject($class, Zend_Db_Select $select)
	{
		$result = $this->_db->fetchRow($select);
		return $this->_createObject($class, $result);
	}
	
	public function _fetchCollection($class, Zend_Db_Select $select)
	{
		$result = $this->_db->fetchAll($select);
		return $this->_createCollection($class, $result);
	}
	
	public function save(Model $object)
	{
		if ($object->isSaved()) {
			$this->_db->update(static::TABLE_NAME, $object->getProperties(), $object->getPK() . " = '" . $object->getPKValue() . "'");
		} else {
			$this->_db->insert(static::TABLE_NAME, $object->getProperties());
			$lastId = $this->_db->lastInsertId();
			$object->setPKValue($lastId);
			$object->setSaved();
		}
	}
	
	public function delete(Model $object)
	{
		$this->_db->delete(static::TABLE_NAME, $object->getPK() . " = '" . $object->getPKValue() . "'");
	}
	
}